package com.nlp.solve;

import com.alibaba.fastjson.JSONObject;
import com.nlp.model.Article;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class SaveAndTransfer {
    private static final Logger logger = LoggerFactory.getLogger(SaveAndTransfer.class);
    private static final String inputDir = "F:\\IdeaProjects\\NLP2.0\\src\\test\\tmp\\";

    public static void main(String[] args) throws IOException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Map<String, List<Article>> map = new HashMap<>();
        File file = new File(inputDir);
        solve(file, map);
        excel(map);
        System.out.println(map.size());
    }

    private static void excel(Map<String, List<Article>> map) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        Workbook workbook = new HSSFWorkbook();
        for (Map.Entry<String, List<Article>> entry : map.entrySet()) {
            //每个国家对应一个sheet
            logger.info("Resolving: {}", entry.getKey());
            Sheet sheet = workbook.createSheet(entry.getKey());
            int index = 0;
            Field[] declaredFields = Article.class.getDeclaredFields();
            Row row0 = sheet.createRow(0);
            row0.createCell(0).setCellValue("id");
            for (int i = 0; i < declaredFields.length; i++) {
                row0.createCell(i + 1).setCellValue(declaredFields[i].getName());
            }
            for (int i = 0; i < entry.getValue().size(); i++) {
                Row row = sheet.createRow(++index);
                int j = 0;
                row.createCell(j).setCellValue(index);
                Article article = entry.getValue().get(i);
                for (int i1 = 0; i1 < declaredFields.length; i1++) {
                    //反射获取Getter方法
                    Method method = Article.class.getDeclaredMethod("get" + declaredFields[i1].getName().toUpperCase(Locale.ROOT));
                    Object val = method.invoke(article);
                    String v = "";
                    if (declaredFields[i1].getType() == String[].class) {
                        String[] tmp = (String[]) val;
                        for (int k = 7; tmp != null && tmp.length > 7 && k < tmp.length; k++) {
                            tmp[k] = null;
                        }
                        v = Arrays.toString(tmp);
                        //System.out.println("length: " + v.length());
                    } else {
                        v = (String) val;
                    }
                    // System.out.println(declaredFields[i1].getName() + ": " + v);
                    try {
                        row.createCell(++j).setCellValue((v == null || "null".equals(v)) ? "" : v);
                    } catch (IllegalArgumentException e) {
                        logger.error(declaredFields[i1].getName()+": "+e.getMessage());
                    }
                }
            }
        }
        try (DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("./all.xlsx")))) {
            workbook.write(dataOutputStream);
        }
    }

    private static void solve(File file, Map<String, List<Article>> map) throws IOException {
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                solve(f, map);
            } else {
                solve_(f, map);
            }
        }
    }

    private static void solve_(File f, Map<String, List<Article>> map) throws IOException {
        String fn = f.getName();
        if (fn.contains("statistic") || fn.contains("issue") || fn.contains("result") | fn.contains("test")) {
            return;
        }
        logger.info("Resolving: {}", f.getAbsolutePath());
        String country = f.getParentFile().getName();
        List<Article> articles = JSONObject.parseArray(Main.read(f.getAbsolutePath()), Article.class);
        map.computeIfAbsent(country, l -> new LinkedList<>()).addAll(articles);
    }
}
